
import { ref, onMounted, onUnmounted, computed, type Ref } from 'vue'

export interface GridLayoutOptions {
  minItemWidth: number // 元素最小宽度
  gap?: number // 元素间距
  defaultPerRow?: number // 默认每行数量
  containerPadding?: number // 容器内边距
}

export interface GridLayoutResult {
  itemsPerRow: Ref<number>
  containerWidth: Ref<number>
  updateLayout: () => void
}

/**
 * 计算每行显示的元素数量
 */
export function useGridLayout(
  containerRef: Ref<HTMLElement | null>,
  options: GridLayoutOptions
): GridLayoutResult {
  const { minItemWidth, gap = 8, defaultPerRow = 1, containerPadding = 0 } = options
  
  const itemsPerRow = ref(defaultPerRow)
  const containerWidth = ref(0)

  const calculateLayout = () => {
    if (!containerRef.value) return
    
    // 获取容器实际可用宽度（减去内边距）
    const availableWidth = containerRef.value.clientWidth - (containerPadding * 2)
    containerWidth.value = availableWidth
    
    if (availableWidth <= 0) {
      itemsPerRow.value = defaultPerRow
      return
    }

    // 计算每行可以容纳的元素数量
    // 每个元素占用的宽度 = 元素宽度 + 间距
    const itemTotalWidth = minItemWidth + gap
    const calculatedPerRow = Math.floor((availableWidth + gap) / itemTotalWidth)
    
    itemsPerRow.value = Math.max(1, calculatedPerRow)
  }

  // 防抖处理
  let resizeTimer: number | null = null
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = window.setTimeout(calculateLayout, 150)
  }

  onMounted(() => {
    calculateLayout()
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    window.removeEventListener('resize', handleResize)
  })

  return {
    itemsPerRow,
    containerWidth,
    updateLayout: calculateLayout
  }
}

/**
 * 根据每行元素数量计算分页大小
 */
export function usePaginationSize(
  itemsPerRow: Ref<number>,
  rowsPerPage: number
) {
  return computed(() => {
    return itemsPerRow.value * rowsPerPage
  })
}